<?php
// may be this the best place to start our session?
session_start();

function tderror_handler($errno, $errstr, $errfile, $errline) {
	$errormessage = "";
	
	if (!(error_reporting() & $errno)) {
		// This error code is not included in error_reporting
		return;
	}

	switch ($errno) {
		case E_USER_ERROR:
			$errormessage .= "*ERROR* [$errno] $errstr\n";
			$errormessage .= "  Fatal error on line $errline in file $errfile";
			$errormessage .= ", PHP " . PHP_VERSION . " (" . PHP_OS . ")\n";
			$errormessage .= "Aborting...\n";
			break;

		case E_USER_WARNING:
			$errormessage .= "*WARNING* [Errno: $errno in $errfile at line $errline] $errstr\n";
			break;

		case E_USER_NOTICE:
			$errormessage .= "*NOTICE* [Errno: $errno in $errfile at line $errline] $errstr\n";
			break;

		default:
			$errormessage .= "Unknown error type: [Errno: $errno in $errfile at line $errline] $errstr\n";
			break;
	}

	global $teardrop;
	if (isset($teardrop->config['log_file'])) {
		error_log($errormessage, 3, $teardrop->config['log_file']);
	}

	if ($errno == E_USER_NOTICE) {
		print("<pre>");
		print($errormessage);
		print("</pre>");
		//exit(1);
		// route to error handling page
		// todo...
		$teardrop->errormessage = $errormessage;
		$teardrop->route("error.htm");
	}
	else {
		print("<pre>");
		print($errormessage);
		print("</pre>");
	}
	
	/* Don't execute PHP internal error handler */
  return true;
}

$perrorlevel = error_reporting();
@error_reporting( (isset($tdconfig['log_level'])) ? $tdconfig['log_level'] : $perrorlevel );
set_error_handler('tderror_handler');

function T() {
	$args = func_get_args();
	
	call_user_func_array("printf", $args);
}


function tdUrl($url) {
	global $teardrop;

	if (substr($url, 0, strlen($teardrop->webroot)-1) != $teardrop->webroot) {
	  $url = $teardrop->webroot."/".$url;
	}
	if (isset($teardrop->arguments['locale'])) {
		$url .= "/locale/".$teardrop->arguments['locale'];
	}
	return $url;
}

function __autoload($class_name) {
  global $sysroot;

  $class_file = str_replace('_', '/',strtolower($class_name)).".php";

  $class_load = $sysroot."/app/".$class_file;
  if (file_exists($class_load)) {
  	require_once $class_load;
  }
  else {  
    $class_load = $sysroot."/lib/components/".$class_file;
    if (file_exists($class_load)) {
      require_once $class_load;
    }
    else {
      $class_load = $sysroot."/lib/classes/".$class_file;
      if (file_exists($class_load)) {
        require_once $class_load;
      }
    }
  }
}
?>
